<template>
  <div class="add-location-page">
    <h1>📦 新增存储位置</h1>
    
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>位置编码：</label>
        <input 
          v-model="form.code" 
          required
          pattern="[A-Z]\d{2}-(SH|BX)\d{2}"
          title="格式示例：A01-SH01"
        >
      </div>

      <div class="form-group">
        <label>位置类型：</label>
        <select v-model="form.type" required>
          <option value="shelf">书架</option>
          <option value="box">储物箱</option>
        </select>
      </div>

      <div class="form-group">
        <label>容量：</label>
        <input 
          v-model.number="form.capacity" 
          type="number" 
          min="1" 
          required
        >
      </div>

      <div class="form-group">
        <label>详细描述：</label>
        <textarea v-model="form.description"></textarea>
      </div>

      <button type="submit">提交添加</button>
      <router-link to="/" class="cancel-btn">取消</router-link>
    </form>
  </div>
</template>

<script>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const form = reactive({
      code: '',
      type: 'shelf',
      capacity: 50,
      description: ''
    })

    const handleSubmit = async () => {
      try {
        const response = await fetch('http://localhost:5000/api/locations', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(form)
        })

        if (!response.ok) throw new Error('添加失败')
        router.push('/?showSuccess=true')
      } catch (err) {
        alert(err.message)
      }
    }

    return { form, handleSubmit }
  }
}
</script>

<style scoped>
.add-location-page {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input, select, textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  background: #2c3e50;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  margin-left: 15px;
  color: #666;
}
</style>